package com.glorystone.ins.service.impl;

import static com.glorystone.ins.common.util.JdbcUtil.isSuccess;

import com.glorystone.ins.common.common.PageVo;
import com.glorystone.ins.common.util.MD5Coding;
import com.glorystone.ins.common.util.ServiceValidate;
import com.glorystone.ins.dao.SysAuthMapper;
import com.glorystone.ins.dao.SysRoleMapper;
import com.glorystone.ins.dao.SysUserMapper;
import com.glorystone.ins.domain.SysAuth;
import com.glorystone.ins.domain.SysRole;
import com.glorystone.ins.domain.SysUser;
import com.glorystone.ins.interceptor.PageList;
import com.glorystone.ins.service.ISysUserService;
import com.glorystone.ins.util.PasswordHelper;

import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@Transactional(readOnly = true)
public class SysUserServiceImpl implements ISysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysAuthMapper sysAuthMapper;


    @Override
    public PageList<SysUser> findUserList(PageVo vo) {
    	
        return sysUserMapper.findUserList(vo, vo.getPageable());
    }

    @Override
    public Set<String> getRoleNameSetByUsername(String username) {
        //TODO 一个用户可能对应多个角色
        SysUser user = sysUserMapper.getUserByUserName(username);
        String roleIds = user.getRoleId();
        String[] roleIdArray = roleIds.split(",");
        Set<String> roles = new HashSet<>();
        for(int i=0;i<roleIdArray.length;i++){
            String roleId = roleIdArray[i].trim();
            if("0".equals(roleId)){
                continue;
            }
            if(!Strings.isNullOrEmpty(roleId)){
                SysRole sysRole = sysRoleMapper.selectByPrimaryKey(Long.parseLong(roleId));
                roles.add(sysRole.getRoleTypeName());
            }
        }
        return roles;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
    public Set<String> getAuthSetByUsername(String username) {
        //TODO 一个用户可能对应多个角色
        SysUser user = sysUserMapper.getUserByUserName(username);
        Set<String> auths = new HashSet<>();
        String roleIds = user.getRoleId();
        String[] roleIdArray = roleIds.split(",");
        for(int i=0;i<roleIdArray.length;i++){
            String roleId = roleIdArray[i].trim();
            if("0".equals(roleId)){
                continue;
            }
            if(!Strings.isNullOrEmpty(roleId)){
                SysRole role = sysRoleMapper.selectByPrimaryKey(Long.parseLong(roleId));
                String authIds = role.getAuthIds();
                List<SysAuth> authList = sysAuthMapper.getAllAuth();
                for(SysAuth s:authList){
                    if(authIds.indexOf(","+s.getTid()+",")>-1){
                        auths.add(s.getText());
                    }
                }
            }
        }
        return auths;
    }

    @Transactional(readOnly = false)
    @Override
    public boolean addUser(SysUser user) {
        ServiceValidate.isTrue(!StringUtils.isEmpty(user), "用户不能为空");
        user.setCreateTime(new Date(System.currentTimeMillis()));
        int result = sysUserMapper.insertSelective(user);
        return result == 1;
    }

    @Transactional(readOnly = false)
    @Override
    public boolean delUser(Long userId) {
        int result = sysUserMapper.deleteByPrimaryKey(userId);
        return result == 1;
    }

    @Transactional(readOnly = false)
    @Override
    public boolean updateUser(SysUser user) {
        //如果id为空 或者对象为空
        if (StringUtils.isEmpty(user) || StringUtils.isEmpty(user.getTid())) {
            ServiceValidate.isTrue(Boolean.FALSE, "用户不能为空");
        }
        user.setUpdateTime(new Date(System.currentTimeMillis()));
        int result = sysUserMapper.updateByPrimaryKeySelective(user);
        boolean state = isSuccess(result);
        ServiceValidate.isTrue(state, "更新失败");
        return state;
    }

    @Override
    public SysUser getUserById(Long userId) {
        return sysUserMapper.selectByPrimaryKey(userId);
    }


    @Override
    public SysUser getUserByUserName(String jobNumber) {
        if (StringUtils.isEmpty(jobNumber)) {
            ServiceValidate.isTrue(Boolean.FALSE, "用户名不能为空");
        }
        SysUser user = sysUserMapper.getUserByUserName(jobNumber);
        if(user != null){

            Set<String> roles = new HashSet<>();
            Set<String> auths = new HashSet<>();
            Map<String,Object> map = new HashMap();
            String roleIds = user.getRoleId();
            String[] roleIdArray = roleIds.split(",");
            int level =3;
            int status =1;
            int deflag =1;
            for(int i=0;i<roleIdArray.length;i++){
                String roleId = roleIdArray[i].trim();
                if("0".equals(roleId)){
                    continue;
                }
                if(!Strings.isNullOrEmpty(roleId)){
                    SysRole sysRole = sysRoleMapper.selectByPrimaryKey(Long.parseLong(roleId));
                    int roleLevel = sysRole.getRoleLevel();
                    int roleStatus = sysRole.getStatus();
                    int roleDelFlag = sysRole.getDelFlag();
                    if(roleLevel<level){
                        level = roleLevel;
                    }
                    if(roleStatus ==0 && roleDelFlag==0){
                        status=0;
                        deflag=0;
                        roles.add(sysRole.getRoleTypeName());
                        String authIds = sysRole.getAuthIds();
                        List<SysAuth> authList = sysAuthMapper.getAllAuth();
                        for(SysAuth s:authList){
                            if(authIds.indexOf(","+s.getTid()+",")>-1){
                                auths.add(s.getText());
                            }
                        }
                    }

                }
            }
            user.setUserLevel(level);
            user.setRoleStatus(status);
            user.setRoleDelFlag(deflag);
            user.setRoles(roles);
            user.setStringPermissions(auths);
        }

        return user;
    }

    @Override
    public SysUser getUserByUserNameAndPwd(String userName, String pwd) {
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(pwd)) {
            ServiceValidate.isTrue(Boolean.FALSE, "用户名或密码不能为空");
        }
       /* MD5Coding.encode()*/
        return sysUserMapper.getUserByUserNameAndPwd(userName, MD5Coding.encode2HexStr(pwd.getBytes()));
    }

    @Transactional(readOnly = false)
    @Override
    public boolean modifyPassword(SysUser user, SysUser u) {
        user.setPassword(u.getPassword());
        user.setSalt(u.getSalt());
        user.setCredentialsSalt(u.getCredentialsSalt());
        //如果id为空 或者对象为空
        if (StringUtils.isEmpty(user) || StringUtils.isEmpty(user.getTid())) {
            ServiceValidate.isTrue(Boolean.FALSE, "用户不能为空");
        }
        user.setUpdateTime(new Date(System.currentTimeMillis()));
        int result = sysUserMapper.modifyPassword(user);
        boolean state = isSuccess(result);
        ServiceValidate.isTrue(state, "更新失败");
        return state;
    }

    @Transactional(readOnly = false)
	@Override
	public boolean updateStatus(SysUser sysuser) {
		int result = sysUserMapper.updateStatus(sysuser);
		return result == 1;
	}

    @Override
    public List<String> getIdsByOfficeId(Long officeId) {
        return sysUserMapper.getIdsByOfficeId(officeId);
    }
    
    @Override    
    public SysUser onlyJobNumber(String jobNumber) {
    	if (StringUtils.isEmpty(jobNumber)) {
            ServiceValidate.isTrue(Boolean.FALSE, "工号不能为空");
        }
		SysUser user = sysUserMapper.onlyJobNumber(jobNumber);
		return user;
	}
	@Override
	public PageList<SysUser> selectUser(PageVo vo) {
		return sysUserMapper.selectUser(vo, vo.getPageable());
	}

	@SuppressWarnings("rawtypes")
	@Transactional(readOnly = false)
	@Override
	public void insertExternalUser(SysUser user) {
		SysRole role = new SysRole();
		Map officeMap = new HashMap();
		List<Map<String, Object>> officeList = sysRoleMapper.getAllInOutDepartment();
    	for (Map<String, Object> map : officeList) {
			if(map.get("level").equals(9)){
				officeMap = map;
			}
		}
    	List<SysRole> roleList = sysRoleMapper.getAllRoleList();
    	for (int i = 0; i < roleList.size(); i++) {
			SysRole sysRole = roleList.get(i);
			if(sysRole.getDepartmentId().equals(officeMap.get("tid"))){
				role = sysRole;
			}
		}
    	user.setOfficeId((long)officeMap.get("tid"));
    	user.setPhone(user.getPhone());
		user.setPassword("qd@123456");
		user.setJobNumber(user.getJobNumber());
		user.setRoleId(""+role.getTid());
		SysUser u = PasswordHelper.encryptPassword(user);
		u.setUsername(user.getJobNumber());
		u.setType(1);
		u.setCreateTime(new Date(System.currentTimeMillis()));
		u.setStatus(0);
		sysUserMapper.insertExternalUser(u);
	}

	@Transactional(readOnly = false)
	@Override
	public boolean resetPassword(SysUser user,SysUser u) {
		System.out.println(user.getPassword());
		user.setPassword(u.getPassword());
		user.setUpdateTime(new Date(System.currentTimeMillis()));
		user.setSalt(u.getSalt());
		user.setCredentialsSalt(u.getCredentialsSalt());
		int result = sysUserMapper.resetPassword(user);
		return result == 1;
	}

	@Override
	public List<SysUser> selectByOfficeId(Long officeId) {
		List<SysUser> list = sysUserMapper.selectByOfficeId(officeId);
		return list;
	}

	@Override
	public SysUser selectById(Long tid) {
		SysUser user = sysUserMapper.selectById(tid);
		return user;
	}

	@Transactional(readOnly = false)
	@Override
	public void updateInsertExternalUser(SysUser user) {
		user.setUpdateTime(new Date(System.currentTimeMillis()));
		sysUserMapper.updateInsertExternalUser(user);
	}

	@Transactional(readOnly = false)
	@Override
	public boolean editLand(Long tid) {
		int result = sysUserMapper.editLand(tid);
		return result == 1;
	}

}
